﻿using NLog;
using EpubFactory.Common;
using EpubFactory.Template;
using EpubFactory.Zhuishu.Model;
using EpubFactory.Zhuishu.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EpubFactory.Zhuishu.UI
{
    public partial class BookDetailForm : Form
    {
        protected static readonly Logger _log = LogManager.GetLogger("bookDetailForm",typeof(BookDetailForm));
        private MixTocInfo mixTocInfo;
        private List<tocChaperInfo> chapters;
        private IEnumerable<TocSummmaryInfo> tocList;
        //EpubFactory.Zhuishu.Model.Book book;
        private IEnumerable<IBookFileCreator> creatorList;
        EpubFactory.Common.Book book;

        public BookDetailForm()
        {
            InitializeComponent();
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //var client = HttpService.GetHttpClient(HttpHelper.USER_AGENT);
            int j = 0;
            book.Chapters = chapters.Select(g => new Chapter()
            {
                Id = g.id,
                Title = g.title,
                Book = book,
                SortOrder = j++,
                Href = g.link
            }).ToList();
            //int i = 0;
            //foreach (var chapter in chapters)
            //{
            //    if (bgWorker.CancellationPending)
            //    {
            //        return;
            //    }
            //    string info = string.Format("正在下载:{0} {1}/{2} ", chapter.title, i + 1, chapters.Count);
            //    bgWorker.ReportProgress((int)i, info);

            //    var chapterInfo = LibZhuiShu.GetChapter(chapter.link);
            //    var m = book.Chapters.First(g => g.Href == chapter.link);
            //    m.Content = chapterInfo.body;
            //    m.SourceContent = chapterInfo.cpContent;
            //    i++;
            //}

            Parallel.ForEach(chapters, (chapter, loop, i) =>
            {
                if (bgWorker.CancellationPending)
                {
                    loop.Stop();
                    return;
                }
                string info = string.Format("正在下载:{1}/{2}  {0}", chapter.title, i + 1, chapters.Count);
                bgWorker.ReportProgress((int)i, info);

                var chapterInfo = LibZhuiShu.GetChapter(chapter.link);
                var m = book.Chapters.First(g => g.Href == chapter.link);
                m.Content = chapterInfo.body;
                m.SourceContent = chapterInfo.cpContent;
            });
            if (bgWorker.CancellationPending)
            {
                return;
            }
            bgWorker.ReportProgress(chapters.Count, "正在生成电子书请稍后....");
            var filePath = Path.Combine(AppPreference.Load().OutputDir, "Books", book.Title);
            var dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            try
            {
                if (creatorList == null)
                {
                    creatorList = BookFileCreatorFactory.GetCreatorList(AppPreference.Load().OutputFormatters);
                }
                foreach (var creator in creatorList)
                {
                    creator.Generate(book, filePath);
                }

                MessageBox.Show("生成成功");
            }
            catch (ArgumentNullException ex)
            {
                _log.Error("生成电子书出错", ex);
                MessageBox.Show(ex.Message, "出错");
            }
        }

        private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbProgress.Value = e.ProgressPercentage;
            if (e.UserState != null)
            {
                statusInfo.Text = e.UserState.ToString();
            }
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnDownload.Text = "下载";
        }
        public void Show(QueryBookInfo queryBook)
        {
            this.book = new EpubFactory.Common.Book()
            {
                Authors = new List<string>() { queryBook.author },
                EPubId = queryBook._id,
                Title = queryBook.title,
                Chapters = new List<Chapter>()
            };
            this.Text = queryBook.title;
            lblName.Text = queryBook.title;
            lblAuthor.Text = string.Format("{0} | {1} | {2}", queryBook.author, queryBook.cat, StringUtil.FormatWordCount(queryBook.wordCount));
            lblLastChapter.Text = string.Format("最新章节:{0}", queryBook.lastChapter);
            lblRatio.Text = string.Format("留存率:{0}", queryBook.retentionRatio);
            txtSummary.Text = queryBook.shortIntro;
            if (!string.IsNullOrWhiteSpace(queryBook.cover) && queryBook.cover.StartsWith("http"))
            {
                pbCover.Load(queryBook.cover);
            }
            else
            {
                pbCover.Image = ImageUtil.Generate(book.Title, book.Authors.FirstOrDefault());
            }
            lblSite.Text = "当前书源:混合源";
            RunAsync(() =>
            {
                mixTocInfo = LibZhuiShu.GetMixToc(queryBook._id);
                if (mixTocInfo != null)
                {
                    chapters = mixTocInfo.chapters.ToList();

                    RunInMainthread(() =>
                    {
                        RenderChapters();
                    });
                }
                tocList = LibZhuiShu.GetTocSummary(queryBook._id);
            });
            this.Show();
        }
        private void RenderChapters()
        {
            lvChapters.BeginUpdate();
            lvChapters.Items.Clear();
            foreach (var chaper in chapters)
            {
                ListViewItem item = new ListViewItem();
                item.Text = chaper.title;
                item.SubItems.Add(chaper.link);
                lvChapters.Items.Add(item);
            }
            lvChapters.EndUpdate();
        }
        private void RunAsync(Action action)
        {
            ((Action)(delegate()
            {
                if (action != null)
                {
                    action.Invoke();
                }
            })).BeginInvoke(null, null);
        }

        private void RunInMainthread(Action action)
        {
            this.BeginInvoke((Action)(delegate()
            {
                if (action != null)
                {
                    action.Invoke();
                }
            }));
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (bgWorker.IsBusy && bgWorker.CancellationPending)
            {
                return;
            }

            if (bgWorker.IsBusy)
            {
                if (bgWorker.IsBusy)
                {
                    bgWorker.CancelAsync();
                    btnDownload.Text = "正在取消";
                }
                return;
            }
            btnDownload.Text = "取消";
            //label_downloadinfo.Text = "即将开始...";
            ResetProgressBar();

            bgWorker.RunWorkerAsync();
        }

        void ResetProgressBar()
        {
            pbProgress.Value = 0;
            pbProgress.Maximum = chapters.Count;
            pbProgress.Visible = true;
        }

        private void BookDetailForm_Load(object sender, EventArgs e)
        {

        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            if (bgWorker.IsBusy)
            {
                MessageBox.Show("下载中,不能更换", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var form = new TocListForm();
            form.Show(mixTocInfo, tocList, (index) =>
            {
                ChangeToc(index);
            });
        }
        void ChangeToc(int index)
        {
            var toc = tocList.ElementAt(index);
            RunAsync(() =>
            {
                var info = LibZhuiShu.GetChaperList(toc._id);
                if (info != null)
                {
                    chapters = info.chapters.ToList();
                }
                RunInMainthread(() =>
                {
                    lblSite.Text = "当前书源:" + toc.name;
                    RenderChapters();
                    ResetProgressBar();
                });
            });
        }
    }
}
